import { createStore } from '@/airstore';
import ApiClient from '@/services/apiClient';
import {
  transPlanStatus,
  transPreflight,
  transPostflight,
  transAirport,
} from './components/taskVFFormat';
import { formatDate } from '@/helpers/dateutil';
function replaceNullStr(str) {
  if (!str || str === 'null') {
    return '';
  }
  return str;
}

//放行任务列表项转换
function transformTask(trd) {
  return {
    id: trd.TS_TaskStageTid,
    flightTid: trd.Tid,
    airplane_no:
      trd.VF_PlaneID && `${trd.VF_PlaneID[0]}-${trd.VF_PlaneID.slice(1)}`, //机号
    taskPaperType: trd.TS_TaskPaperType, //级别
    taskCount: trd.TS_TaskCount, //任务数
    preflight: transPreflight(trd), //前序航班
    postflight: transPostflight(trd), //后序航班
    airport: transAirport(trd), //站点
    bay: replaceNullStr(trd.VF_Bay), //机位
    passPer: replaceNullStr(trd.TS_User_Name), //放行人员
    areaOrWorker: replaceNullStr(trd.TS_Tech), //区域负责人 工作者
    finishPersent: trd.TS_Persent, //完成状况
    taskStatus: trd.TS_TaskStatus, //状态
  };
}

// 航线 定检任务 转换
function transformPassObj(trd) {
  return {
    id: trd.Tid || trd.TS_TasktTid,
    taskStageTid: trd.TS_TaskStageTid,
    cardTitle: trd.MpDp_CardTitle, //工卡标题
    jobCard: trd.MpDp_JobCard, //工卡号
    workOrder: trd.MpDp_WorkOrder, //指令号
    workPer: replaceNullStr(trd.R3), //工作者
    planDate: trd.MpDp_PlanDate, //计划执行日期
    finishDate: trd.MpDp_Date, //完工日期
    planStatus: trd.MpDp_PlanStatus, //状态
    planStatusDes: transPlanStatus(trd.MpDp_PlanStatus), //状态
  };
}
//DDFC 转换
function transformDdfcObj(ddfcItem, index) {
  return {
    index: index + 1,
    id: ddfcItem.Tid,
    acno: ddfcItem.MDF_Acno,
    ddfcNo: ddfcItem.MDF_DDF_No,
    version: ddfcItem.MDF_VERSION,
    ata: ddfcItem.ATA,
    description: ddfcItem.MDF_Description,
    reason: ddfcItem.MDF_Reason,
    date: ddfcItem.MDF_Date,
    cat: ddfcItem.MDF_Cat,
    limitTime: ddfcItem.MDF_Hours, //截止日期
    status: ddfcItem.MDF_Man, //状态
    mhrs: ddfcItem.MDF_MHRS, //重复执行
    jobCardUrl: ddfcItem.MDF_RECFITICATEION, //附件地址
  };
}

export default createStore({
  namespace: 'ReleaseJob',
  filterCond: {
    startDate: null,
    endDate: null,
    selAirport: '',
    selAirplane: '',
    taskStatus: 99,
  },
  list: [],
  scPassDetail: [],
  scPassInfo: null,
  flightPassDetail: [],
  flightPassInfo: null,
  fleetMonitorInfo: [],
  ddfcInfo: [],
  setJobList(jbData, filter) {
    if (jbData) {
      this.list = jbData.map(transformTask);
    } else {
      this.list = [];
    }
    this.filterCond = filter;
  },
  setScPassDetail(spdData) {
    this.scPassDetail = spdData.map((spd) => spd.map(transformPassObj));
  },
  setFlightPassDetail(fpdData) {
    this.flightPassDetail = fpdData.map((spd) => spd.map(transformPassObj));
  },
  setDdFcAndFleetInfo(ddfcData) {
    this.ddfcInfo = ddfcData.map(transformDdfcObj);
  },
  // 获取定检SC放行详细信息
  setScPassInfo(passData) {
    if (passData.length !== 0) {
      const scInfo = {
        taskStageTid: passData.TS_TaskStageTid,
        flightTid: passData.flightTid,
        Name: passData[0].TS_PassOperator_Name,
        date: formatDate(passData[0].TS_Pass_Time, 'YYYY-MM-DD HH:mm:ss'),
      };
      this.scPassInfo = scInfo;
    } else {
      this.scPassInfo = null;
    }
  },
  // 获取非定检放行详细信息
  setPassInfo(passData) {
    if (passData.length !== 0) {
      const fpPassInfo = {
        taskStageTid: passData.TS_TaskStageTid,
        flightTid: passData.flightTid,
        Name: passData[0].TS_PassOperator_Name,
        date: formatDate(passData[0].TS_Pass_Time, 'YYYY-MM-DD HH:mm:ss'),
        checkValue: passData[0].R1,
        oiladd1: passData[0].TS_LeftENG_SN,
        oiladd2: passData[0].TS_RightENG_SN,
      };
      this.flightPassInfo = fpPassInfo;
    } else {
      this.flightPassInfo = null;
    }
  },
  // 获取放行任务列表
  async getJobList(loginName, filter) {
    const searchPara = {
      datefrom: filter.startDate.format('YYYY-MM-DD'),
      dateto: filter.endDate.format('YYYY-MM-DD'),
      stationid: filter.selAirport,
      acno: filter.selAirplane,
      taskStatus: filter.taskStatus ? (filter.taskStatus === '1' ? 4 : 99) : 0,
    };
    const srRes = await ApiClient.post('mpController/v1/getPassTask', {
      loginUser: loginName,
      jsonResult: JSON.stringify(searchPara),
    });
    this.setJobList(!srRes.errorCode ? srRes.data : null, filter);
    return srRes;
  },
  /**
   * SC放行任务详情
   *
   * @param {*} loginName
   * @param {*} taskStageTid
   * @param {*} flightTid
   * @return {*}
   */
  async getScPassJobDetail(loginName, taskStageTid, flightTid) {
    const scPara = {
      taskStageTid: taskStageTid,
      flightTid: flightTid,
    };
    const srRes = await ApiClient.post('mpController/v1/getPassDetailSc', {
      loginUser: loginName,
      jsonResult: JSON.stringify(scPara),
    });
    this.setScPassDetail(srRes.data || []);
    return srRes;
  },
  /**
   * 交换区域任务区域地址
   *
   * @param {*} jobId
   * @param {*} oldAreaIndex
   * @param {*} newAreaIndex
   */
  swipePassDetailByArea(jobId, oldAreaIndex, newAreaIndex) {
    this.scPassDetail = this.scPassDetail.map((scpd, idx) => {
      if (idx === oldAreaIndex) {
        return scpd.filter((scp) => scp.id !== jobId);
      } else if (idx === newAreaIndex) {
        return this.scPassDetail[oldAreaIndex]
          .filter((scp) => scp.id === jobId)
          .concat(scpd);
      }
      return scpd;
    });
  },
  /**
   * 指派任务区域
   *
   * @param {string} loginName - 当前用户名
   * @param {number} jobId - 任务id
   * @param {string} newArea - 新区域名
   * @param {number} oldAreaIndex - 当前区域序号
   * @param {number} newAreaIndex - 新区域序号
   * @return {ApiResponse}
   */
  async designateJobArea(
    loginName,
    jobId,
    newArea,
    oldAreaIndex,
    newAreaIndex,
  ) {
    const scPara = {
      taskTid: jobId,
      areaValue: newAreaIndex,
    };
    const srRes = await ApiClient.post('mpController/v1/changeArea', {
      loginUser: loginName,
      jsonResult: JSON.stringify(scPara),
    });
    if (!srRes.errorCode) {
      this.swipePassDetailByArea(jobId, oldAreaIndex, newAreaIndex);
    }
    return srRes;
  },
  /**
   * SC/航线任务放行确认
   *
   * @param {string} loginUser - 当前用户名
   * @param {*} passPara
   * @return {ApiResponse}
   */
  async passTask(loginUser, passPara) {
    const srRes = await ApiClient.post('mpController/v1/taskPass', {
      loginUser: loginUser,
      jsonResult: JSON.stringify(passPara),
    });
    return srRes;
  },
  /**
   * 航线放行任务详情
   *
   * @param {*} loginName
   * @param {*} taskStageTid
   * @param {*} flightTid
   * @return {*}
   */
  async getFlightPassDetail(loginName, taskStageTid, flightTid) {
    const scPara = {
      taskStageTid: taskStageTid,
      flightTid: flightTid,
    };
    const srRes = await ApiClient.post('mpController/v1/getPassDetail', {
      loginUser: loginName,
      jsonResult: JSON.stringify(scPara),
    });
    this.setFlightPassDetail(srRes.data || []);
    return srRes;
  },
  /**
   * 航线任务派工选中状态
   *
   * @param {*} detailIndex
   * @param {*} flightDetailId
   * @param {*} checked
   */
  switchAssignCheck(detailIndex, flightDetailId, checked) {
    this.flightPassDetail = this.flightPassDetail.map((scpd, idx) => {
      if (idx === detailIndex) {
        return scpd.map((scp) => {
          if (scp.id === flightDetailId) {
            return { ...scp, assignChecked: checked };
          }
          return scp;
        });
      }
      return scpd;
    });
  },
  /**
   * 取消航线任务选中
   *
   */
  cancelAssignRepairer() {
    this.flightPassDetail = this.flightPassDetail.map((scpd) =>
      scpd.map((scpdd) => ({
        ...scpdd,
        assignChecked: false,
      })),
    );
  },
  //派工
  async assignTaskRepairer(loginName, passPara) {
    const srRes = await ApiClient.post('mpController/v1/taskToRepair', {
      loginUser: loginName,
      jsonResult: JSON.stringify(passPara),
    });
    return srRes;
  },
  /**
   * 退回任务
   *
   * @param {*} taskId
   * @param {*} paraCheck
   * @param {*} remarkTxt
   * @return {*}
   */

  async returnTask(loginName, taskTid, paraCheck, paraMemo) {
    const returnPara = {
      taskTid: taskTid,
      paraCheck: paraCheck,
      paraMemo: paraMemo,
    };
    const srRes = await ApiClient.post('mpController/v1/taskReturn', {
      loginUser: loginName,
      jsonResult: JSON.stringify(returnPara),
    });
    return srRes;
  },
  // 获取放行详细信息
  async getPassInfo(loginName, taskStageTid, taskPaperType) {
    const passPara = {
      taskStageTid: taskStageTid,
      taskPaperType: taskPaperType,
    };
    const srRes = await ApiClient.post('mpController/v1/getPassInfo', {
      loginUser: loginName,
      jsonResult: JSON.stringify(passPara),
    });
    if (taskPaperType === 'SC') {
      this.setScPassInfo(srRes.data || []);
    } else {
      this.setPassInfo(srRes.data || []);
    }
    return srRes.data;
  },
  //验证是否可以放行
  async verifyPass(loginName, taskStageTid, flightTid) {
    const passPara = {
      taskStageTid: taskStageTid,
      flightTid: flightTid,
    };
    const srRes = await ApiClient.post('mpController/v1/ifCanPass', {
      loginUser: loginName,
      jsonResult: JSON.stringify(passPara),
    });
    return srRes;
  },
  //ddfc
  async getDdFcAndFleetMonitor(loginName, ddfcPara) {
    const srRes = await ApiClient.post('zoController/v1/getDdfcList', {
      loginUser: loginName,
      jsonResult: JSON.stringify(ddfcPara),
    });
    if (!srRes.errorCode) {
      this.setDdFcAndFleetInfo(srRes.data || []);
    }
    return srRes.data;
  },
});
